package com.woniu.fly.fairmall.core.system;

import com.woniu.fly.fairmall.core.util.SystemInfoPrinter;
import com.woniu.fly.fairmall.db.service.FairmallSystemConfigService;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class SystemInitService {

    @Resource
    private Environment environment;

    @Resource
    private FairmallSystemConfigService fairmallSystemConfigService;

    // 预设的默认配置,在静态快中配置
    private final static Map<String, String> DEFAULT_CONFIGS = new HashMap<>();
    static {
        DEFAULT_CONFIGS.put(SystemConfig.FAIR_MALL_TEST, "测试无敌");
    }

    @PostConstruct
    private void init() {
        initConfigs();
        SystemInfoPrinter.printInfo("初始化信息", getSystemInfo());
    }

    private void initConfigs() {
        // 1. 读取数据库全部配置信息
        Map<String, String> configs = fairmallSystemConfigService.queryAllConfig();
        // 2. 分析DEFAULT_CONFIGS
        for (Map.Entry<String, String> entry : DEFAULT_CONFIGS.entrySet()) {
            if(configs.containsKey(entry.getKey())){
                continue;
            }
            configs.put(entry.getKey(), entry.getValue());
            fairmallSystemConfigService.addConfig(entry.getKey(), entry.getValue());
        }
        SystemConfig.setConfigs(configs);
    }

    private Map<String, String> getSystemInfo(){
        Map<String, String> infos = new LinkedHashMap<>();

        infos.put(SystemInfoPrinter.CREATE_PART_COPPER + 0, "系统信息");
        // 测试获取application-db.yml配置信息
        infos.put("服务器端口", environment.getProperty("server.port"));
        infos.put("数据库USER", environment.getProperty("spring.datasource.druid.username"));
        infos.put("数据库地址", environment.getProperty("spring.datasource.druid.url"));
        infos.put("调试级别", environment.getProperty("com.woniu.fly.fairmall.db"));

        //测试获取System表配置信息
        infos.put(SystemInfoPrinter.CREATE_PART_COPPER + 1, "系统设置");
        infos.put("首页显示记录数：TEST", SystemConfig.getTest());
        return infos;
    }
}
